/**
 * 简单的店铺设置脚本
 * 快速创建店铺并关联商品
 */

const mongoose = require('mongoose');
require('dotenv').config();

// 简单的连接和数据创建
async function setupShops() {
  try {
    // 连接数据库
    await mongoose.connect(process.env.MONGODB_URI);
    console.log('数据库连接成功');

    // 获取集合
    const shopsCollection = mongoose.connection.db.collection('shops');
    const productsCollection = mongoose.connection.db.collection('products');
    const usersCollection = mongoose.connection.db.collection('users');

    // 创建测试用户
    const testUser = {
      _id: new mongoose.Types.ObjectId(),
      name: '测试店主',
      email: 'test@shop.com',
      password: 'password123',
      createdAt: new Date(),
      updatedAt: new Date()
    };

    await usersCollection.deleteMany({});
    await usersCollection.insertOne(testUser);
    console.log('创建测试用户成功');

    // 创建测试店铺
    const testShops = [
      {
        _id: new mongoose.Types.ObjectId(),
        name: 'Apple官方旗舰店',
        description: 'Apple官方授权旗舰店，正品保证',
        logo: 'https://picsum.photos/200/200?random=101',
        banner: 'https://picsum.photos/800/300?random=201',
        owner: testUser._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码'],
        rating: {
          overall: 4.9,
          service: 4.9,
          logistics: 4.8,
          description: 4.9
        },
        certification: {
          isVerified: true,
          verifiedAt: new Date()
        },
        shipping: {
          freeShippingThreshold: 0,
          shippingFee: 0,
          supportedRegions: ['全国'],
          averageDeliveryTime: 1
        },
        afterSales: {
          returnPolicy: '15天无理由退货',
          warrantyPeriod: 365,
          supportRefund: true,
          supportExchange: true
        },
        stats: {
          totalProducts: 0,
          totalSales: 10000,
          totalOrders: 5000,
          monthlyRevenue: 500000,
          followers: 50000
        },
        followers: [],
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        _id: new mongoose.Types.ObjectId(),
        name: '小米官方旗舰店',
        description: '小米科技官方旗舰店',
        logo: 'https://picsum.photos/200/200?random=102',
        banner: 'https://picsum.photos/800/300?random=202',
        owner: testUser._id,
        type: 'official',
        status: 'active',
        categories: ['手机数码'],
        rating: {
          overall: 4.8,
          service: 4.8,
          logistics: 4.7,
          description: 4.8
        },
        certification: {
          isVerified: true,
          verifiedAt: new Date()
        },
        shipping: {
          freeShippingThreshold: 99,
          shippingFee: 10,
          supportedRegions: ['全国'],
          averageDeliveryTime: 2
        },
        afterSales: {
          returnPolicy: '7天无理由退货',
          warrantyPeriod: 365,
          supportRefund: true,
          supportExchange: true
        },
        stats: {
          totalProducts: 0,
          totalSales: 15000,
          totalOrders: 8000,
          monthlyRevenue: 300000,
          followers: 80000
        },
        followers: [],
        createdAt: new Date(),
        updatedAt: new Date()
      }
    ];

    // 清空并创建店铺
    await shopsCollection.deleteMany({});
    await shopsCollection.insertMany(testShops);
    console.log('创建测试店铺成功');

    // 获取所有商品并关联到店铺
    const products = await productsCollection.find({}).toArray();
    console.log(`找到 ${products.length} 个商品`);

    if (products.length > 0) {
      // 将商品分配给店铺
      for (let i = 0; i < products.length; i++) {
        const shopIndex = i % testShops.length;
        const assignedShop = testShops[shopIndex];
        
        await productsCollection.updateOne(
          { _id: products[i]._id },
          { $set: { shop: assignedShop._id } }
        );
        
        console.log(`商品 "${products[i].name}" 分配给 "${assignedShop.name}"`);
      }

      // 更新店铺商品统计
      for (const shop of testShops) {
        const productCount = await productsCollection.countDocuments({ shop: shop._id });
        await shopsCollection.updateOne(
          { _id: shop._id },
          { $set: { 'stats.totalProducts': productCount } }
        );
        console.log(`${shop.name}: ${productCount} 个商品`);
      }
    }

    console.log('✅ 店铺设置完成！');
    
  } catch (error) {
    console.error('❌ 设置失败:', error);
  } finally {
    await mongoose.connection.close();
    console.log('数据库连接已关闭');
  }
}

setupShops();
